import store from '@/store'
import axios from 'axios'
import Vue from 'vue'
import { Loading,Message,MessageBox } from 'element-ui'
// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
	baseURL: 'http://127.0.0.1:8080',
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config)

_axios.interceptors.request.use(
  function(config) {
	config.headers.common['token'] = store.getters.GET_TOKEN
	// Do something before request is sent
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
)

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    return response;
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error);
  }
)
function request(url,method,params,callback) {
	const loading = Loading.service({
		lock: true,
		text: method === 'get' ? '拼命加载中' : '数据提交中',
		spinner: 'el-icon-loading',
		background: 'rgba(0, 0, 0, 0.5)'
	})
	let lm_config = {
		url: url,
		method: method
	}
	if( method === 'post') {
		const formData = new FormData()
		for(let key in params) {
			formData.append(key,params[key])
		} 
		lm_config.data = formData
	} else {
		lm_config.params = params
	}
	_axios(lm_config).then(response => {
		if(response.data.code === 500) {
			Message.error(response.data.obj)
		} else if (response.data.code === 200) {
			callback(response.data)
		} else {
			Message.error(response.data.message)
		}
	}).catch(error => {
		Message.error(error)
	}).finally(() => {
		loading.close()
	})
}
Vue.prototype.$axios = {
	get(url,params,callback) {
		request(url,'get',params,callback)
	},
	post(url,params,callback,formobj) {
		let flag = new Promise( (resolve) => {
			if(formobj) {
				formobj.validate( valid => {
					resolve(valid)
				})
			} else {
				resolve(true)
			}
		})
		flag.then( resp => {
			if(resp) {
				request(url,'post',params,(response) => {
					Message.success(response.message)
					callback(response)
				})
			}
		})
	},
	del(url,params,method,callback) {
		const text = params.active === 0 ? '确定要删除数据吗?' : '确定要恢复数据吗?'
		const msg = params.active === 0 ? '删除成功' : '恢复成功'
		const icon = params.active === 0 ? 'warning' : 'success'
		MessageBox.confirm(text,'操作提示',{
			type: icon
		}).then(() => {
			if(params.ids && params.ids.length === 0) {
				Message.info('没有要删除的项')
			}
			request(url,method,params,response => {
				if(response.obj) {
					Message.success(msg)
				}
				callback(response)
			})
		})
	}
}
